import React, { Component } from 'react'
import PubSub from 'pubsub-js'

export default class index extends Component {
    state = {
        userList: [],
        isFirst: true,  // 是否为第一次打开页面
        isLoading: false, // 是否处于加载中
        err: '', //
    }

    componentDidMount(){
        console.log('this',this);
        this.temporary = PubSub.subscribe('dataObj',(_,data)=>{
            console.log('subscribe',_,data);
            this.setState(data)
        })
    }

    componentWillUnmount(){
        // 取消订阅
        PubSub.unsubscribe(this.temporary)
        // console.log('this.temporary',this.temporary);
    }

    render() {
        const { userList, isFirst, isLoading, err } = this.state

        return (
            <div className="row">
                {
                    isFirst ? <h2>欢迎使用，输入关键字，点击</h2> :
                        isLoading ? <h2>Loading......</h2> :
                            err ? <h2 style={{ color: 'red' }}>{err}</h2> :
                                userList.map(el => {
                                    return <div className="card" key={el?.id}>
                                        <a href="https://github.com/reactjs" target="_blank">
                                            <img src={el?.avatar_url} style={{ width: '100px' }} />
                                        </a>
                                        <p className="card-text">reactjs</p>
                                    </div>
                                })
                }
            </div>
        )
    }
}
